from tkinter import *
import time
import math
import random
from mymodule.game_02_base import GameBase
from mymodule.game_02_base import Environment
from mymodule.game_02_base import Border
    
class BallGame(GameBase):
    def __init__(self):
        super().__init__()
    
            
    def check_hit_ball(self, ball1, ball2):
        # 计算两个球之间的距离
        distance = math.sqrt((ball1.x - ball2.x) ** 2 + (ball1.y - ball2.y) ** 2)
    
        # 如果两个球之间的距离小于等于两个球半径之和，则认为它们发生了碰撞
        if distance <= ball1.radius + ball2.radius:
        # 反弹
            if(ball1.radius > ball2.radius):
                ball2.velocity_x *= -1
                ball2.velocity_y *= -1
            
            elif(ball1.radius == ball2.radius):
                ball1.velocity_x *= -1
                ball1.velocity_y *= -1
                ball2.velocity_x *= -1
                ball2.velocity_y *= -1
            else:
                ball1.velocity_x *= -1
                ball1.velocity_y *= -1
                
          
     
    def run(self):
        border = Border(100,700,100,500)
        self.make_wall(border.left,border.top,border.right-border.left,border.bottom-border.top)
        
        
        # 准备一个有多个球的“列表”
        balls = [
                self.make_ball(100, 150, 20,  "darkblue"),
                self.make_ball(200, 250, 25,  "orange"),
                self.make_ball(300, 350, 10,  "green"),
                self.make_ball(400, 450, 5, "darkgreen")
                ]
        
       
        while True:
             for ball in balls:
                self.move_ball(ball)
                self.check_hit_wall(ball, border)
                self.redraw_ball(ball)
                #check ball hit ball 
                for other_ball in balls:
                    if ball != other_ball:
                        self.check_hit_ball(ball, other_ball)
                self.tk.update()
                time.sleep(Environment.DURATION)
            
game = BallGame()
game.run()